<!DOCTYPE html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="./cactbot/defaults.css">
    <link rel="stylesheet" href="./cactbot/resize_handle.css">
    <script src="./cactbot/common.js"></script>
    <script src="./common.js"></script>
    <script src="./cactbot/resize_handle.js"></script>
    <script src="./vue.min.js"></script>
    <script src="./vue_ccino_select.js"></script>
    <link rel="stylesheet" href="./vue_ccino_select.css">
    <script src="./axios.min.js"></script>
    <script src="./log_config.js"></script>
    <link href="./index.css?v=6" rel="stylesheet" />
</head>
<body class="noselect">
    <div id="container" :style="{fontSize:option.fontSize+'px', 'background-color':option.colors.background}" v-cloak @dblclick="openSetting">
        <template v-if="option.settingOnFrontpage.server">
            <ccino-select :options="serverList" v-model="option.selectedServer" v-slot:prefix="slotProps" @change="saveOption">
                本地服务器: 
            </ccino-select>
        </template>
        <template v-if="option.settingOnFrontpage.zone">
            <ccino-select :options="zoneList" v-model="option.selectedZone" @change="saveOption">
                <template v-slot:prefix="slotProps">
                    区域: 
                </template>
                <template v-slot:default="slotProps">
                    <span v-if="slotProps.value.brackets"><small>{{slotProps.value.brackets.min}}.0</small></span> {{zoneName[slotProps.value.id]}}
                </template>
            </ccino-select>
            <ccino-select :options="option.selectedZone.encounters" v-model="option.selectedEncounter" @change="saveOption">
                <template v-slot:prefix="slotProps">
                    BOSS: 
                </template>
                <template v-slot:default="slotProps">
                    {{slotProps.value.name}} 
                </template>
            </ccino-select>
        </template>
        <div v-if="logData&&logData.character" style="margin-top:30px;">
            <ul>
                <li style="flex: 0 0 80%;text-align: left;" >{{logData.character.name}}❀{{logData.character.server}}</li>
                <li style="flex: 0 0 20%;text-align: center;" ><span class="log-data" :class="getLogsGrade(logData.highestLog)">{{logData.highestLog||"无"}}</span></li>
            </ul>
            <template v-if="option.logsInfoShowDetail">
                <div class="title-border"></div>
                <ul v-for="ranks,encounterName in logData.rankings_format">
                    
                    <li :style="{flex: '0 0 '+(option.logsInfoEncounterNameWidth||30)+'%'}" style="text-align: left;" >{{encounterName}} </li>
                    <li class="log-data" :style="{flex: '0 0 '+(100-(option.logsInfoEncounterNameWidth||30))+'%'}">
                        <span v-for="rank in ranks" style="white-space: nowrap;
                        display: inline-block;">
                            <img class="log-job-img" 
                                :src="'./icons/'+(rank.job||'Err')+'.png'" 
                                onerror="this.style.opacity='0'"/>
                            <span :class="getLogsGrade(rank.logs)" class="log-data">{{rank.logs}}</span>
                            &nbsp;
                        </span>
                    </li>
                    
                </ul>
            </template>
        </div>
    </div>
    <script>
        'use strict';
        for(var zone of zoneList){
            if(!zone.encounters){
                zone.encounters=[];
            }
            zone.encounters.unshift({"name":"<未选择>"});
        }
        zoneList.sort(function(a,b){ return b.id-a.id;});
        var defaultOption = {
            fontSize: 13,
            colors: {
                background: "rgba(0,0,0,0.2)"
            },
            apiKey:"1dec8751508fa8e36cde7c53b550b69b",
            supportLogsInfo:true,
            logsInfoShownDuration:10,
            logsInfoEncounterNameWidth:30,
            logsInfoShowDetail:true,
            selectedZone:zoneList[zoneList.length-4],
            selectedEncounter:zoneList[zoneList.length-4].encounters[0],
            selectedServer: serverList[0],
            settingOnFrontpage:{
                server:true,
                zone:true,
            }
        };
        var savedOption = localStorage.getItem("CCINO_LOGS_OPTION");
        if (savedOption) {
            savedOption = JSON.parse(savedOption);
        }
        function getOption(option) {
            option = mergeObj(JSON.parse(JSON.stringify(defaultOption)), option);
            return option;
        }

        var vueapp = new Vue({
            el: "#container",
            data: {
                option: getOption(savedOption),
                logData:{},
                zoneList:zoneList,
                zongName:zoneName,
                serverList:serverList,
            },
            methods: {
                openSetting:function(){
                    if (vueapp.settingWindow) {
                        vueapp.settingWindow.focus();
                        return;
                    }
                    vueapp.settingWindow = openWindow("./logs_setting.html", "_blank", 960, 300);
                    localStorage.setItem("CCINO_LOGS_OPTION", JSON.stringify(vueapp.option));
                    var loop = setInterval(function () {
                        if (!vueapp.settingWindow || vueapp.settingWindow.closed) {

                            clearInterval(loop);
                            vueapp.settingWindow = null;

                            vueapp.option = getOption(JSON.parse(localStorage.getItem("CCINO_LOGS_OPTION")));
                            setLogInfoSupport();
                            resetLogShowTimer();
                        }
                    }, 300);
                },
                saveOption:function(){
                    localStorage.setItem("CCINO_LOGS_OPTION",JSON.stringify(vueapp.option));
                },
                getLogsGrade:function(log){
                    var grades=[100,99,95,75,50,25];
                    for(let g of grades){
                        if(log>=g){
                            return "log-"+g;
                        }
                    }
                    return "log-9";
                }
            }
        });
        (function(){
            //-------------LOGS获取
            let logsCache={};
            function getCharacterName(fullname){
                for(let server of serverList){
                    if(fullname.substr(fullname.length-server.length)===server){
                        return [fullname.substr(fullname.length-server.length),fullname.substr(0,fullname.length-server.length)];
                    }
                }
                return [,fullname];
            }
            function getRankings(fullname,callback){
                if(!fullname) return;
                fullname=getCharacterName(fullname);
                let serverName=fullname[0],characterName=fullname[1];
                let option=vueapp.option;
                if(!serverName) serverName=option.selectedServer;
                let cacheKey=`${serverName}_${characterName}_${option.selectedZone.id}_${option.selectedEncounter.id}`;
                if(logsCache[cacheKey]){
                    let logData=logsCache[cacheKey];
                    updateLogData(logData);
                    if(callback instanceof Function){
                        callback(logData);
                    }
                    return;
                }
                let character={name:characterName,server:serverName};
                serverName=encodeURIComponent(serverName);
                characterName=encodeURIComponent(characterName);
                let url=`https://cn.fflogs.com/v1/rankings/character/${characterName}/${serverName}/CN?timeframe=historical&api_key=${option.apiKey}`;
                if(option.selectedZone && option.selectedZone.id){
                    url+="&zone="+option.selectedZone.id;
                    if(option.selectedEncounter&&option.selectedEncounter.id){
                        url += "&encounter=" + option.selectedEncounter.id;
                    }
                }
                axios.get(url).then(res => {
                    let highestLog=0;
                    let rankings=[];
                    for(let r of res.data){
                        r.percentile=Math.round(r.percentile);
                        if(r.encounterID >= 65 && r.encounterID <= 68 && r.difficulty != 101){
                            continue;
                        }
                        rankings.push(r);
                        if(r.percentile>highestLog){
                            highestLog=r.percentile;
                        }
                    }
                    let logData={
                        character:character,
                        rankings:rankings,
                        highestLog:highestLog
                    }
                    logsCache[cacheKey]=logData;
                    updateLogData(logData);
                    if(callback instanceof Function){
                        callback(logData);
                    }
                }).catch(err => {
                    console.log(err)
                })
            }
            function checkLogs(fullname){
                getRankings(fullname,function(logData){
                    let speakLog=logData.highestLog||"无log";
                    if(callOverlayHandler){
                        callOverlayHandler({
                            call: 'cactbotSay',
                            text: `${logData.character.name}:${speakLog}`,
                        });
                    }
                });
            }
            window.checkLogs=checkLogs;

            //-------------LOGS显示
            let timer;
            function resetLogShowTimer(){
                if(timer!=null){
                    clearInterval(timer);
                    timer=null;
                }
                timer=setInterval(function(){
                    clearInterval(timer);
                    vueapp.logData={};
                },Math.round((vueapp.option.logsInfoShownDuration||10)*1000));
            }
            window.resetLogShowTimer=resetLogShowTimer;
            function updateLogData(logData){
                logData.rankings_format={};
                for(let ranking of logData.rankings){
                    if(!logData.rankings_format[ranking.encounterName]){
                        logData.rankings_format[ranking.encounterName]=[];
                    }
                    logData.rankings_format[ranking.encounterName].push({
                        logs:ranking.percentile,
                        job:jobNameCnToType[ranking.spec],
                        spec:ranking.spec
                    });
                }
                vueapp.logData=logData;
                resetLogShowTimer();
            }
            function logInfoCallback(e){
                for (let logLine of e.detail.logs) {
                    // console.log(logLine);
                    let r = logLine.match(/([^:]*?)加入了小队/);
                    if(!r) r = logLine.match(/00:0038:logs\s+([^:\s]*)/);
                    if (r) {
                        // console.log(r);
                        checkLogs(r[1]);
                    }
                }
            }
            window.setLogInfoSupport=function(){
                if(removeOverlayListener){ //先尝试删除
                    removeOverlayListener('onLogEvent', logInfoCallback);
                }
                if(addOverlayListener){
                    addOverlayListener('onLogEvent', logInfoCallback);
                }
            }

            setLogInfoSupport();
        }())
        function openWindow(url, name, iWidth, iHeight) {
            return window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
        }
    </script>
</body>